package net.lengwang.iot.middleware.packet;

import net.lengwang.iot.middleware.network.HandshakePacket;

public class PacketFactory {
    // 命令位常量
    public static final byte CMD_HANDSHAKE = (byte) 0x90;
    // 在这里添加其他命令位常量

    // 起始标志位常量
    public static final byte[] START_FLAG = new byte[]{(byte) 0xBE, (byte) 0xBE};

    // 结束标志位常量
    public static final byte[] END_FLAG = new byte[]{(byte) 0xEB, (byte) 0xEB};

    // 数据包总长度常量
    public static final byte PACKET_LENGTH = 0x04;

    public static Packet createPacket(byte[] data) {
        if (data.length < 4) {
            throw new IllegalArgumentException("Invalid packet length");
        }

        // 验证起始标志位
        if (data[0] != START_FLAG[0] || data[1] != START_FLAG[1]) {
            throw new IllegalArgumentException("Invalid start flag");
        }

        // 验证数据包总长度
        if (data[2] != PACKET_LENGTH) {
            throw new IllegalArgumentException("Invalid packet length");
        }

        Packet packet;
        switch (data[3]) {
            case CMD_HANDSHAKE:
                packet = new HandshakePacket();
                break;
            // 在这里添加更多数据包类型
            default:
                throw new IllegalArgumentException("Unknown packet type: " + String.format("%02X", data[3]));
        }

        packet.fromBytes(data);

        // 验证结束标志位
        if (data[data.length - 2] != END_FLAG[0] || data[data.length - 1] != END_FLAG[1]) {
            throw new IllegalArgumentException("Invalid end flag");
        }

        return packet;
    }
}
